var express = require('express');
var router = express.Router();
const validator = require('validator');
const Dbset = require('../model/db');
const Games = require('../model/Games');
const Reply = require('../model/Reply');
const Article = require('../model/Article')
const setting = require('../setting');
const saveMessage = require('../common/message');
var multer = require('multer')
var storage = multer.diskStorage({
  destination: 'public/images',
  filename: function (req, file, cb) {
    console.log(file)
    cb(null, file.fieldname + '-' + Date.now() + '.jpg')
  }
})
//创建对象
var upload = multer({ storage: storage })
// upload.array('文件名',文件数量)批量处理文件
/* GET home page. */
router.get('/', function (req, res, next) {
  // console.log('123')

  res.render('index', { title: 'Express' });
});
router.get('/logoin', function (req, res, next) {
  // console.log('123')

  res.render('logoin', { title: '登录' });
});
router.get('/zhuce', function (req, res, next) {
  // console.log('123')

  res.render('zhuce', { title: '注册' });
});
router.post('/upload', upload.array('photo', 10), (req, res, next) => {
  console.log(req.body)
  // console.log(req.files)
  const arr = []
  req.files.forEach(function (imgs) {
    arr.push(imgs.filename)
  })
  Games.findOne({ "gameid": req.body.gameid }, (err, game) => {
    if (game) {
      return res.json({ error: 1, message: "编号重复" })
    }
    console.log(game)
    // console.log(arr)
    var game = new Games()
    game.gameid = req.body.gameid;
    game.gamename = req.body.gamename;
    game.gameer = req.body.gameer;
    game.gamemotto = req.body.gamemotto;
    game.gameer_poeple = req.body.gameer_poeple;
    game.gameprize = req.body.gameprize;
    game.gametype = req.body.gametype;
    game.gametime = new Date;
    game.game_big = req.body.game_big;
    game.gameer_bimg = arr
    game.save().then((game) => {
      res.json({ error: 0, message: "发布成功" })
    }).catch((error) => {
      res.json({ error: 1, message: "发布失败" })
    })
  })


})
router.get('/game', function (req, res, next) {
  // var arr = []
  Games.find((err, game) => {
    // console.log(game)
    if (err) {
      return res.json({ error: 1, message: '没有游戏' })
    }
    // arr.push(game)
    res.render('game', {
      title: 'Game',
      game: game
    })
  })
})
router.get('/updata/:_id', function (req, res, next) {
  console.log(req.params._id)
  Games.findOne({ "_id": req.params._id }, function (err, game) {
    console.log(game)
    res.render('updata', {
      title: '123'
    })
  })

})
router.get('/shanchu/:id', function (req, res, next) {
  Games.findByIdAndRemove({ "_id": req.params.id }, function (err) {
    res.json({ error: 0, message: "删除成功" })
  })
})


module.exports = router;
